package com.citycloud.ccuap.tc.sync.aspect;

import com.citycloud.ccuap.commons.json.JSONData;
import com.citycloud.ccuap.commons.sys.entity.SysDistrict;
import com.citycloud.ccuap.tc.sync.constant.GlobalSyncOperation;
import com.citycloud.ccuap.tc.sync.constant.GlobalSyncType;
import com.citycloud.ccuap.tc.sync.dto.SyncDataDto;
import com.citycloud.ccuap.tc.sync.dto.SysDistrictMessageDTO;
import com.citycloud.ccuap.tc.sync.service.IMessageService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author zhangxu
 * @create 2020/7/13
 * Description:
 */
@Aspect
@Component
public class DistrictUpdateAspect {
    @Autowired
    private IMessageService messageService;

    @Pointcut("execution(* com.citycloud.ccuap.commons.sys.district.DistrictController.update())")
    public void update() {
    }

    @AfterReturning(value = "update()", returning = "key")
    public void doAddDept(JoinPoint joinPoint, Object key) throws Throwable {
        if (key instanceof JSONData) {
            JSONData jsonData = (JSONData) key;
            if (jsonData.getData() instanceof SysDistrict) {
                SysDistrict sysDistrict = (SysDistrict) jsonData.getData();
                sendMessage(sysDistrict);
            }
        }
    }

    private void sendMessage(SysDistrict sysDistrict) {
        SysDistrictMessageDTO sysDistrictMessageDTO = new SysDistrictMessageDTO();
        sysDistrictMessageDTO.build(sysDistrict);

        SyncDataDto<SysDistrictMessageDTO> result = SyncDataDto.of(GlobalSyncType.OBJECT_TYPE_DISTRICT,
                GlobalSyncOperation.UPDATED, null, sysDistrictMessageDTO);
        messageService.sendMessageByTopic(result,GlobalSyncType.TOPIC_DISTRICT);
    }

}
